<template>
  <!-- hidden PageHeaderWrapper title demo -->
  <page-header-wrapper :title="false">
    <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
      <a-form @submit="handleAdd" :form="this.form">
        <a-form-item
          label="商品分类"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-select placeholder="请选择" v-decorator="['typeId']" @change="changeType">
            <a-select-option :value="i.id" v-for="i in this.option" :key="i.value">{{ i.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="商品名"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-select
            v-decorator="['product', { rules: [{ required: true, message: '请选择' }] }]"
            placeholder="请选择"
            @select="handleSelect"
          >
            <a-select-option :value="i.id" v-for="i in this.prodOption" :key="i.value">{{ i.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="成本"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-input
            v-decorator="['commCost', { rules: [{ required: true, message: '请输入' }] }]"
            addonAfter="元"
            placeholder="请输入成本"
            name="commCost"
          />
        </a-form-item>
        <a-form-item
          label="串码模式"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-radio-group v-decorator="['chuanma', { initialValue: '1' }]" placeholder="请选择">
            <a-radio :style="radioStyle" value="1">单串码模式</a-radio>
            <a-radio :style="radioStyle" value="2">双串码模式</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          label="串码"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-textarea
            rows="8"
            placeholder="可添加多个,每行一个串码，错误的串码会被过滤掉"
            v-decorator="['phoneCodeList', { rules: [{ required: true, message: '请输入' }] }]"
          />
        </a-form-item>
        <a-form-item
          label="往来账"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-radio-group
            v-decorator="['isRecord', { initialValue: 1, rules: [{ required: true, message: '请选择' }] }]"
            placeholder="请选择"
          >
            <a-radio :style="radioStyle" :value="1">记录供应商往来账</a-radio>
            <a-radio :style="radioStyle" :value="2">不记录供应商往来账</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item :wrapperCol="{ span: 24 }" style="text-align: center">
          <a-button htmlType="submit" type="primary" icon="check">添加</a-button>
          <!-- <a-button style="margin-left: 8px">{{ $t('form.basic-form.form.save') }}</a-button> -->
        </a-form-item>
      </a-form>
    </a-card>
    <a-card :body-style="{ padding: '24px 32px' }" title="入库商品清单">
      <template #extra>
        <a-tooltip>
          <template #title> {{ `${isDetail ? '切换入库详情' : '切换入库汇总'} ` }}</template>
          <a-button type="primary" icon="swap" @click="handleCheck(queryParam)"></a-button>
        </a-tooltip>
      </template>
      <a-table
        ref="table"
        size="default"
        rowKey="key"
        :columns="isDetail ? hzColumns : columns"
        :data-source="isDetail ? hzLoadData : loadData"
      >
        <span slot="isRecord" slot-scope="text, record">
          <template>
            <div v-if="record.isRecord == 1">是</div>
            <div v-else>否</div>
          </template>
        </span>

        <span slot="heji" slot-scope="text, record">
          <template>
            {{ record?.price * record?.total }}
          </template>
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a-tag color="#D15B47" @click="handleDel(record)">删除</a-tag>
          </template>
        </span>
      </a-table>
    </a-card>
    <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
      <a-form @submit="handleSubmit" :form="form1">
        <a-form-item
          label="供应商"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-select
            v-decorator="['supplyId', { rules: [{ required: true, message: '请选择' }] }]"
            placeholder="请选择供应商"
          >
            <a-select-option :value="i.id" v-for="i in this.suppliesOption" :key="i.value">{{
              i.name
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="采购渠道"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-select v-decorator="['channelId']" placeholder="请选择">
            <a-select-option :value="i.id" v-for="i in this.channelOption" :key="i.value">{{ i.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="入库日期"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-date-picker
            v-decorator="['orderDate', { initialValue: this.toDays, rules: [{ required: true, message: '请选择' }] }]"
            valueFormat="YYYY-MM-DD"
          />
        </a-form-item>
        <a-form-item
          label="二次入库"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-radio-group
            v-decorator="['isSecond', { initialValue: 1, rules: [{ required: true, message: '请选择' }] }]"
            placeholder="请选择"
          >
            <a-radio :style="radioStyle" :value="0">不允许二次入库</a-radio>
            <a-radio :style="radioStyle" :value="1">允许二次入库</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          label="备注"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-input v-decorator="['memo']" name="memo" placeholder="请输入备注" />
        </a-form-item>
        <a-form-item :wrapperCol="{ span: 24 }" style="text-align: center">
          <a-button htmlType="submit" type="primary" icon="check">提交入库</a-button>
        </a-form-item>
      </a-form>
    </a-card>
  </page-header-wrapper>
</template>
<script>
import { getSuppliesListUsingPOST } from '@/api/api/jingxiaoshangyunyingshangguanli.ts'
import { getGdClassListUsingPOST, getGoodsListUsingPOST } from '@/api/api/shangpinguanli.ts'
import { getChannelListUsingPOST, manualPurchaseUsingPOST } from '@/api/api/caigouguanli.ts'
import moment from 'moment'
export default {
  name: 'InStoreDetail',
  data() {
    return {
      radioStyle: {
        display: 'block',
        height: '30px',
        lineHeight: '30px',
      },
      toDays: moment().format('YYYY-MM-DD'),
      isDetail: false,
      params: {
        buyType: 1,
        channelId: '',
        detailParamList: [],
        memo: '',
        orderDate: '',
        storeId: '',
        supplyId: '',
      },
      queryParam: {
        pageNo: 1,
        pageSize: 999,
        queryCondition: '',
        status: 1,
      },
      option: [],
      prodOption: [],
      suppliesOption: [],
      channelOption: [],
      form: this.$form.createForm(this),
      form1: this.$form.createForm(this),
      hzColumns: [
        {
          title: '商品名',
          dataIndex: 'goodName',
        },
        {
          title: '单价',
          dataIndex: 'price',
        },
        {
          title: '数量',
          dataIndex: 'total',
        },
        {
          title: '合计(元)',
          dataIndex: 'heji',
          scopedSlots: { customRender: 'heji' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '220px',
          scopedSlots: { customRender: 'action' },
        },
      ],
      columns: [
        {
          title: '商品名',
          dataIndex: 'goodName',
        },
        {
          title: '串码',
          dataIndex: 'phoneCode1',
        },
        {
          title: '串码2',
          dataIndex: 'phoneCode2',
        },
        {
          title: '成本(元)',
          dataIndex: 'commCost',
        },
        {
          title: '记供应商账',
          dataIndex: 'isRecord',
          scopedSlots: { customRender: 'isRecord' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '220px',
          scopedSlots: { customRender: 'action' },
        },
      ],
      hzLoadData:[],
      nameList:[],
      // 加载数据方法 必须为 Promise 对象
      loadData: [],
    }
  },
  created() {
    this.handleSearch(this.queryParam)
    this.handleProd()
    this.handleSupplies()
    this.handleChannel()
  },
  methods: {
    getRepeatNum(){
      return this.nameList.reduce((prev,next)=>{
        prev[next] = (prev[next] + 1) || 1
        return prev
      },{})
    },
    handleCheck(params) {
      this.isDetail = !this.isDetail
    },
    handleSelect(e) {
      this.form.setFieldsValue({ commCost: this.prodOption.find((i) => i.id == e).commCost })
    },
    handleChannel() {
      getChannelListUsingPOST(this.queryParam)
        .then((res) => {
          this.channelOption = res.data.list
        })
        .catch((error) => {
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },
    handleSupplies() {
      getSuppliesListUsingPOST(this.queryParam)
        .then((res) => {
          this.suppliesOption = res.data.list
        })
        .catch((error) => {
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },
    removeTrim(array) {
      for (let i = 0; i < array.length; i++) {
        if (array[i] == '') {
          array.splice(i, 1)
          i = i - 1
        }
      }
      return array
    },
    handleDel(record) {
      const that = this
      that.$confirm({
        title: '删除',
        content: '你确定要删除这个商品吗？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          that.loadData.splice(
            that.loadData.findIndex((item) => item.id === record.id),
            1
          )
          // this.loadData = this.loadData
        },
      })
    },
    handleAdd(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          const includes = this.loadData
            .map((item) => item.phoneCode1)
            .includes(this.removeTrim(values.phoneCodeList.split('\n'))[0])

          if (!!includes) {
            this.$message.error('存在相同串码')
            return false
          }
          if (values.chuanma == '2') {
            this.loadData.push({
              ...values,
              phoneCode1: this.removeTrim(values.phoneCodeList.split('\n'))[0],
              phoneCode2: this.removeTrim(values.phoneCodeList.split('\n'))[1],
              goodName: this.prodOption.find((item) => {
                return item.id == values.product
              })?.name,
              goodId: this.prodOption.find((item) => {
                return item.id == values.product
              })?.id,
            })
          } else {
            this.removeTrim(values.phoneCodeList.split('\n')).forEach((item) => {
              this.loadData.push({
                ...values,
                phoneCode1: item,
                phoneCode2: '',
                goodName: this.prodOption.find((item) => {
                  return item.id == values.product
                })?.name,
                goodId: this.prodOption.find((item) => {
                  return item.id == values.product
                })?.id,
              })
            })
          }
          for (var i = 0; i < this.loadData.length; i++) {
                var obj = {
                  commCost: this.loadData[i].commCost,
                  inventoryId: this.loadData[i].inventoryId,
                  phoneCode1: this.loadData[i].phoneCode1,
                  goodName: this.loadData[i].goodName,
                  num: this.loadData[i].num ?? 0,
                }
                this.hzLoadData.push(obj)
            }
          this.hzLoadData = this.hzLoadData.filter((item, index) =>this.hzLoadData.findIndex(i => i.goodName === item.goodName) === index)
            this.nameList = this.loadData.map(item => item.goodName)
            const outPriceObj = {}
            this.loadData.forEach(v => outPriceObj[v.goodName] = outPriceObj[v.goodName] === undefined ? v.commCost : outPriceObj[v.goodName] + v.commCost)
            const myObj = this.getRepeatNum()
            this.hzLoadData = this.hzLoadData.map((item)=>{
              return {
                ...item,
                total:myObj[item.goodName],
                price:(outPriceObj[item.goodName] / myObj[item.goodName]).toFixed(2)
              }
            })
          this.form.setFieldsValue({ phoneCodeList: '' })
        }
      })
    },
    handleSearch() {
      getGdClassListUsingPOST({ ...this.queryParam, classType: 2 })
        .then((res) => {
          this.option = res.data.list.map((item) =>{
            return {
              ...item,
            }
          })
        })
        .catch((error) => {
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },
    handleProd(classId) {
      getGoodsListUsingPOST({ ...this.queryParam, classId: classId })
        .then((res) => {
          this.prodOption = res.data.list
        })
        .catch((error) => {
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },
    changeType(e) {
      this.handleProd(e)
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form1.validateFields((err, values) => {
        if (!err) {
          if (this.loadData.length == 0) {
            this.$message.error('没有可入库的商品')
            return false
          }
          const params = {
            isSecond: values.isSecond,
            memo: values.memo,
            orderDate: values.orderDate,
            supplyId: values.supplyId,
            storeId: this.$route.params.id,
            channelId: values.channelId,
            buyType: 1,
          }
          const data = {
            manualPurchaseDataList: this.loadData.map((item) => {
              return {
                brandName: item.brandName,
                commCost: item.commCost,
                goodClass2: item.classId,
                goodsId: item.goodId,
                goodsName: item.goodName,
                isRecord: item.isRecord,
                phoneCode1: item.phoneCode1,
                phoneCode2: item.phoneCode2,
              }
            }),
          }

          manualPurchaseUsingPOST({ ...params }, [...data.manualPurchaseDataList])
            .then((res) => {
              this.$message.success('操作成功')
              this.$router.push({ path: `/purchasing/inStoreRecord/detail/${res.data.id}` })
              this.form.resetFields()
              this.form1.resetFields()
            })
            .catch((error) => {
              this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
            })
        }
      })
    },
  },
}
</script>
